<template>
  <el-card class="overview-container">
    <div class="header">
      <div class="title">{{ t("home.todoTask.title") }}</div>
      <el-select
        v-model="selectedDoctor"
        class="name-select"
        :placeholder="t('home.todoTask.selectDoctor')"
        size="small"
        @change="handleDoctorChange"
      >
        <el-option
          v-for="doctor in doctorList"
          :key="doctor.value"
          :label="doctor.label"
          :value="doctor.value"
        />
      </el-select>
    </div>

    <div class="task-cards">
      <div class="task-card" @click="handleTodayTaskClick">
        <div class="card-header">
          <div class="task-title">
            {{ t("home.todoTask.taskCards.todayTaskPlan") }}
          </div>
          <div class="task-status" :style="taskStatusStyle">
            {{ t("home.todoTask.status.pending") }}
          </div>
        </div>
        <div class="task-number">{{ taskData.todayTaskCount || 0 }}</div>
      </div>

      <div class="task-card" @click="handlePendingSubmitClick">
        <div class="card-header">
          <div class="task-title">
            {{ t("home.todoTask.taskCards.fillFollowupRecord") }}
          </div>
          <div class="task-status" :style="taskStatusStyle">
            {{ t("home.todoTask.status.pendingSubmit") }}
          </div>
        </div>
        <div class="task-number">
          {{ taskData.pendingSubmitTaskCount || 0 }}
        </div>
      </div>

      <div class="task-card" @click="handlePendingReviewClick">
        <div class="card-header">
          <div class="task-title">
            {{ t("home.todoTask.taskCards.riskAssessmentAdvice") }}
          </div>
          <div class="task-status" :style="taskStatusStyle">
            {{ t("home.todoTask.status.pendingReview") }}
          </div>
        </div>
        <div class="task-number">
          {{ taskData.pendingReviewTaskCount || 0 }}
        </div>
      </div>
    </div>

    <!-- 待提交任务抽屉 -->
    <el-drawer
      v-model="pendingSubmitDrawerVisible"
      :title="t('home.todoTask.drawer.fillFollowupPlan')"
      direction="rtl"
      size="600px"
    >
      <div class="pending-submit-drawer">
        <div v-loading="pendingSubmitLoading" class="task-list">
          <div v-if="pendingSubmitTasks.length === 0" class="empty-state">
            <div class="empty-text">
              {{ t("home.todoTask.drawer.noSubmitTasks") }}
            </div>
          </div>
          <div v-else>
            <div
              v-for="(task, index) in pendingSubmitTasks"
              :key="task.reportId"
              class="task-item"
            >
              <!-- 时间信息 -->
              <div class="task-time">
                {{ formatTime(task.startDate) }}
              </div>

              <!-- 任务内容 -->
              <div class="task-content">
                <div class="task-user">
                  {{ task.userName }}
                  <span v-if="task.familyMemberName" class="family-member">
                    ({{ task.familyMemberName }})
                  </span>
                </div>

                <!-- 操作按钮 -->
                <div class="task-action">
                  <el-link type="primary" @click="handleSubmitTask(task)">{{
                    t("home.todoTask.drawer.goToFill")
                  }}</el-link>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 待审核任务抽屉 -->
    <el-drawer
      v-model="pendingReviewDrawerVisible"
      :title="t('home.todoTask.drawer.riskAssessmentAndAdvice')"
      direction="rtl"
      size="600px"
    >
      <div class="pending-submit-drawer">
        <div v-loading="pendingReviewLoading" class="task-list">
          <div v-if="pendingReviewTasks.length === 0" class="empty-state">
            <div class="empty-text">
              {{ t("home.todoTask.drawer.noSubmitTasks") }}
            </div>
          </div>
          <div v-else>
            <div
              v-for="(task, index) in pendingReviewTasks"
              :key="task.reportId"
              class="task-item"
            >
              <!-- 时间信息 -->
              <div class="task-time">
                {{ task.submitUserName }} | {{ formatTime(task.submitTime) }}
              </div>

              <!-- 任务内容 -->
              <div class="task-content">
                <div class="task-user">
                  <div>
                    {{ task.userName }}
                    <span v-if="task.familyMemberName" class="family-member">
                      ({{ task.familyMemberName }})
                    </span>
                  </div>
                  <div>
                    {{ task.institution }} | {{ task.reportTypeName }} |
                    {{ formatTime(task.inspectionDate) }}
                  </div>
                </div>

                <!-- 操作按钮 -->
                <div class="task-action">
                  <el-link type="primary" @click="handleReviewTask(task)">{{
                    t("home.todoTask.drawer.goToReview")
                  }}</el-link>
                </div>
                <div
                  class="type-text"
                  :class="task.type === 1 ? 'isNotHealth' : 'isHealth'"
                >
                  {{
                    task.type === 1
                      ? t("home.todoTask.taskTypes.riskAssessment")
                      : t("home.todoTask.taskTypes.healthAdvice")
                  }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
  </el-card>
</template>

<script lang="ts" setup>
import { followApi } from "@/api/follow";
import dayjs from "dayjs";
import { ElMessage } from "element-plus";
import { computed, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";

import {
  homeApi,
  type HomeTaskData,
  type PendingReviewTaskItem,
  type PendingSubmitTaskItem
} from "@/api/home";

const router = useRouter();
// 国际化
const { t, locale } = useI18n();

// 根据语言状态动态调整task-status样式
const taskStatusStyle = computed(() => {
  // 英文状态下调整字体大小和宽度
  return locale.value === "en"
    ? {
        fontSize: "14px",
        width: "69px"
      }
    : {};
});

// 响应式数据
const selectedDoctor = ref("");
const doctorList = ref<Array<{ label: string; value: string }>>([]);
const loading = ref(false);
const taskData = ref<HomeTaskData>({
  todayTaskCount: 0,
  pendingSubmitTaskCount: 0,
  pendingReviewTaskCount: 0
});

// 抽屉相关状态
const pendingSubmitDrawerVisible = ref(false);
const pendingReviewDrawerVisible = ref(false);
const pendingSubmitTasks = ref<PendingSubmitTaskItem[]>([]);
const pendingReviewTasks = ref<PendingReviewTaskItem[]>([]);
const pendingSubmitLoading = ref(false);
const pendingReviewLoading = ref(false);

// 格式化时间
const formatTime = (time: string) => {
  return dayjs(time).format("YYYY-MM-DD HH:mm:ss");
};

// 获取医生列表
const getDoctorList = async () => {
  try {
    loading.value = true;
    const response = await followApi.getFollowUpPlanDoctorHealthManager();

    if (response.code === 0 && response.data) {
      // 根据实际返回的数据结构调整映射
      doctorList.value = response.data.map((item: any) => ({
        label: item.userName,
        value: item.userId
      }));

      // 如果有数据，默认选择第一个
      // if (doctorList.value.length > 0) {
      //   selectedDoctor.value = doctorList.value[0].value;
      //   // 选择第一个医生后，加载待办任务数据
      //   await getTaskData();
      // }
    }
  } catch (error) {
    console.error("获取医生列表失败:", error);
    ElMessage.error("获取医生列表失败");
  } finally {
    loading.value = false;
  }
};

// 获取待办任务数据
const getTaskData = async () => {
  try {
    const response = await homeApi.getHomeTaskStats(selectedDoctor.value);

    if (response.code === 0 && response.data) {
      taskData.value = response.data;
    }
  } catch (error) {
    console.error("获取待办任务数据失败:", error);
    ElMessage.error("获取待办任务数据失败");
  }
};

// 医生选择变化处理
const handleDoctorChange = async (value: string) => {
  console.log("选择的医生:", value);
  // 重新加载待办任务数据
  await getTaskData();
};

// 获取待提交任务列表
const getPendingSubmitTasks = async () => {
  try {
    pendingSubmitLoading.value = true;
    const response = await homeApi.getPendingSubmitTasks();

    if (response.code === 0 && response.data) {
      pendingSubmitTasks.value = response.data;
    }
  } catch (error) {
    console.error("获取待提交任务列表失败:", error);
    ElMessage.error("获取待提交任务列表失败");
  } finally {
    pendingSubmitLoading.value = false;
  }
};

// 获取待审核任务列表
const getPendingReviewTasks = async () => {
  try {
    pendingReviewLoading.value = true;
    const response = await homeApi.getPendingReviewTasks();

    if (response.code === 0 && response.data) {
      pendingReviewTasks.value = response.data;
    }
  } catch (error) {
    console.error("获取待审核任务列表失败:", error);
    ElMessage.error("获取待审核任务列表失败");
  } finally {
    pendingReviewLoading.value = false;
  }
};
// 点击事件处理
const handleTodayTaskClick = () => {
  // 跳转到今日任务页面
  router.push("/followUpPlan/index"); // 根据实际路由路径调整
};

const handlePendingSubmitClick = async () => {
  pendingSubmitDrawerVisible.value = true;
  await getPendingSubmitTasks();
};

const handlePendingReviewClick = async () => {
  pendingReviewDrawerVisible.value = true;
  await getPendingReviewTasks();
};
const handleSubmitTask = (task: PendingSubmitTaskItem) => {
  router.push({
    path: "/followUpPlan/detail",
    query: {
      taskId: task.taskId,
      userId: task.userId
    }
  });
};
const handleReviewTask = (task: PendingReviewTaskItem) => {
  router.push({
    path: "/report/detail",
    query: {
      reportId: task.reportId.toString(),
      mode: "view"
    }
  });
};

// 组件挂载时获取医生列表
onMounted(() => {
  getDoctorList();
  getTaskData();
});
</script>

<style lang="scss" scoped>
.overview-container {
  border-radius: 16px !important;
  margin-bottom: 16px;

  :deep(.el-card__body) {
    padding: 16px 0;
  }

  .header {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    padding: 0 16px;

    .title {
      font-size: 16px;
      font-weight: 500;
      color: #333;
      position: relative;
      padding-left: 12px;
      margin-right: 32px;

      &::before {
        content: "";
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 16px;
        background: linear-gradient(270deg, #61fffb 0%, #65c8ff 100%);
        box-shadow: 0px 2px 16px 0px rgba(41, 127, 128, 0.06);
        border-radius: 2px;
      }
    }
    .name-select {
      width: 120px;
    }
  }

  .task-cards {
    display: flex;
    gap: 16px;
    padding: 0 16px;
    justify-content: space-evenly;
  }

  .task-card {
    width: 420px;
    height: 160px;
    background-image: url("@/assets/images/home/task_bg.png");
    background-size: cover;
    background-position: center;
    padding: 25px 53px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    cursor: pointer;
    transition: transform 0.2s ease;
    &:hover {
      transform: translateY(-2px);
    }
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
    }

    .task-title {
      font-weight: 500;
      font-size: 16px;
      color: #222222;
      text-shadow: 0px 2px 16px rgba(41, 127, 128, 0.06);
    }

    .task-number {
      font-weight: 600;
      font-size: 40px;
      color: #222222;
      text-shadow: 0px 2px 16px rgba(41, 127, 128, 0.06);
    }

    .task-status {
      font-weight: 600;
      font-size: 20px;
      color: #2dafff;
      letter-spacing: 4px;
      text-shadow: 0px 2px 16px rgba(41, 127, 128, 0.06);
    }
  }
}

/* 待提交任务抽屉样式 */
.pending-submit-drawer {
  height: 100%;
  display: flex;
  flex-direction: column;

  .task-list {
    flex: 1;
    padding: 16px;

    .empty-state {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 200px;

      .empty-text {
        color: #999;
        font-size: 14px;
      }
    }

    .task-item {
      margin-bottom: 24px;
      background: #ffffff;
      border-radius: 8px;
      border: 1px solid #ebebeb;
      padding: 16px;
      position: relative;

      &:last-child {
        margin-bottom: 0;
      }

      .task-time {
        font-weight: 400;
        font-size: 14px;
        color: rgba(0, 0, 0, 0.65);
        padding-bottom: 16px;
      }

      .task-content {
        .task-user {
          font-weight: 500;
          font-size: 14px;
          color: rgba(0, 0, 0, 0.85);
          padding-bottom: 16px;
          border-bottom: 1px solid #e8e8e8;
        }

        .task-action {
          margin-top: 12px;
          display: flex;
          justify-content: center;
        }

        .type-text {
          width: 64px;
          height: 20px;
          position: absolute;
          top: 0;
          right: 0;
          border-radius: 2px 8px 2px 8px;
          font-weight: 400;
          font-size: 12px;
          color: #ffffff;
          text-align: center;
          line-height: 20px;
        }
        .isHealth {
          background: #38d38a;
        }
        .isNotHealth {
          background: #ffb634;
        }
      }
    }
  }
}
</style>
